<?php

namespace app\api\logic;

use think\Model;
use think\Db;
use PHPQRCode;
use think\Session;
class UserLogic extends Model
{

    /**
     * 用户注册
     * $info 用户信息
     */
    static function reg_user($info){
        $data = array(
            'avatar'=>$info['headimgurl'],
            'nickname'=>$info['nickname'],
            'openid'=>$info['openid'],
            'p_id'=>0,
            'number'=>time().mt_rand(1000,9999),
            'c_time'=>time(),
            'token'=>md5(time().mt_rand(1000,9999))
        );
        $id = M('users')->insertGetId($data);
        return $id;
    }
    /**
     * 验证token
     * @param $token string
     * @return bool
     */
    static function check_token($token)
    {
        $user = M('users')->where(array('token' => $token))->find();
        if (!empty($user)) {
            $time = time() + 604800;//604800是七天
            if ($user['last_login'] > $time) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /*
    * 获取token
    */
    static function get_token()
    {
        $str = md5(uniqid(md5(microtime(true)), true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }

    /*
    * 发送验证码
    */
    static public function send_code($mobile, $session_id)
    {
//发送短信验证码

//判断是否存在验证码
        $data = M('sms_log')->where(array('mobile' => $mobile, 'session_id' => $session_id, 'status' => 1))->order('id DESC')->find();
//获取时间配置
        $sms_time_out =  120;
//120秒以内不可重复发送
        if ($data && (time() - $data['add_time']) < $sms_time_out) {
            $return_arr = array('status' => -1, 'msg' => $sms_time_out . '秒内不允许重复发送');
            return $return_arr;
        }
//随机一个验证码
        $code = mt_rand(100000, 999999);
//发送短信
        $resp = self::sendSmsByAlidayu( $mobile, $code, $session_id);

        if ($resp['status'] == 1) {
//发送成功, 修改发送状态位成功
            M('sms_log')->where(array('mobile' => $mobile, 'code' => $code, 'session_id' => $session_id, 'status' => 0))->save(array('status' => 1));
            $return_arr = array('status' => 1, 'msg' => '发送成功,请注意查收');
        } else {
            $return_arr = array('status' => -1, 'msg' => '发送失败' . $resp['msg']);
        }
        return $return_arr;
    }

    /*
    * 验证验证码
    */
    static public function check_code($mobile, $code, $scene=1)
    {
        if (!$code) return array('status' => -1, 'msg' => '请输入短信验证码');
//短信
        $sms_time_out =  120;
        $data = M('sms_log')->where(array('mobile' => $mobile, 'status' => 1))->order('id DESC')->find();
        $timeOut = $data['add_time'] + $sms_time_out;
        if ($data['code'] == $code) {
            $inValid = true;
        } else {
            $inValid = false;
        }
        if (empty($data)) {
            $res = array('status' => -1, 'msg' => '请先获取验证码');
        } elseif ($timeOut < time()) {
            $res = array('status' => -1, 'msg' => '验证码已超时失效');
        } elseif (!$inValid) {
            $res = array('status' => -1, 'msg' => '验证失败,验证码有误');
        } else {
            $res = array('status' => 1, 'msg' => '验证成功');
        }
        return $res;
    }
    /*
    * 生成二维码
    */
    static public function create_qrcode($data)
    {
        require_once ROOT_PATH.'vendor/aferrandini/phpqrcode/lib/PHPQRCode.php';
        error_reporting(E_ERROR);
        $path = ROOT_PATH.'public/qrcode/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        } elseif (!file_exists($path . 'sign_qrcode.png')) {
            PHPQRCode\QRcode::png($data, $path . 'sign_qrcode.png');
        }
    }
    /*
    * 生成二维码
     *
    */
    static public function activity_qrcode($data)
    {
        require_once ROOT_PATH.'vendor/aferrandini/phpqrcode/lib/PHPQRCode.php';
        error_reporting(E_ERROR);
        $path = ROOT_PATH.'public/activity/';
        $name = mt_rand(1111,9999).time().'.png';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        } elseif (!file_exists($path . $name)) {
            PHPQRCode\QRcode::png($data, $path . $name);
        }
        $url ='http://'. $_SERVER['HTTP_HOST'].'/activity/'.$name;
        return $url;
    }

    /**
     * 发送短信（阿里大于）
     * @param $mobile  手机号码
     * @param $code    验证码
     * @return bool    短信发送成功返回true失败返回false
     */
    private static function sendSmsByAlidayu($mobile, $code,$session_id)
    {
        //发送记录存储数据库
        $log_id = M('sms_log')->insertGetId(array('mobile' => $mobile, 'code' => $code, 'add_time' => time(), 'session_id' => $session_id, 'status' => 0, 'scene' => 1));
        if ($mobile != '' && check_mobile($mobile)) {//如果是正常的手机号码才发送
            try {
                require_once ROOT_PATH.'vendor/api_sdk/SmsDemo.php';
                $resp = SmsDemo::sendSms($mobile,array('code'=>$code),"SMS_137685436");
            } catch (\Exception $e) {
                $resp_a = ['status' => -1, 'msg' => $e->getMessage()];
            }
            if ($resp->Code == 'OK') {
                $resp_a = ['status' => 1, 'msg' => $resp->Message];
                M('sms_log')->where(array('id' => $log_id))->update(array('status' => 1)); //修改发送状态为成功
            }else{
                M('sms_log')->where(array('id' => $log_id))->update(array('error_msg'=>$resp->Message)); //发送失败, 将发送失败信息保存数据库
            }
            return $resp_a;
        } else {
            return $result = ['status' => -1, 'msg' => '接收手机号不正确['.$mobile.']'];
        }
    }
    static function set_session($key,$value,$time){
        $time_now = time();
        $res = M('session')->where('key',$key)->find();
        if(empty($res)){
            $data = [
                'key'=>$key,
                'value'=>serialize($value),
                'time'=>$time+$time_now
            ];
            M('session')->insert($data);
        }else{
            $data = [
                'value'=>serialize($value),
                'time'=>$time+$time_now
            ];
            M('session')->where('key',$key)->update($data);
        }
    }
    static function get_session($key){
        $v = M('session')->where('key',$key)->find();
        if(empty($v)){
            return false;
        }
        $time = time();
        if($v['time'] <$time){
            return false;
        }
        return unserialize($v['value']);
    }
    /**
     * 发送短信（阿里大于）
     * @param $mobile  手机号码
     * @param $status    审核状态
     * @return bool    短信发送成功返回true失败返回false
     */
    public static function sendSms($mobile,$status)
    {
        //发送记录存储数据库
        $log_id = M('sms_log')->insertGetId(array('mobile' => $mobile, 'code' => $status, 'add_time' => time(), 'session_id' => 1, 'status' => 0, 'scene' => 1));
        if ($mobile != '' && check_mobile($mobile)) {//如果是正常的手机号码才发送
            try {
                require_once ROOT_PATH.'vendor/api_sdk/SmsDemo.php';
                $resp = SmsDemo::sendSms($mobile,array('status'=>$status),'SMS_150741391');
            } catch (\Exception $e) {
                $resp_a = ['status' => -1, 'msg' => $e->getMessage()];
            }
            if ($resp->Code == 'OK') {
                $resp_a = ['status' => 1, 'msg' => $resp->Message];
                M('sms_log')->where(array('id' => $log_id))->update(array('status' => 1)); //修改发送状态为成功
            }else{
                $resp_a = ['status' => -1, 'msg' => $resp->Message];
                M('sms_log')->where(array('id' => $log_id))->update(array('error_msg'=>$resp->Message)); //发送失败, 将发送失败信息保存数据库
            }
            return $resp_a;
        } else {
            return $result = ['status' => -1, 'msg' => '接收手机号不正确['.$mobile.']'];
        }
    }



}